import { BrowserWindow } from "electron";
import { startListen, type MsgHandler } from "blive-message-listener";

const handler: MsgHandler = {
  onIncomeDanmu: msg => {
    sendToAllWindow("Danmu", msg.body);
  },
  onGift: msg => {
    sendToAllWindow("Gift", msg.body);
  },
  onGuardBuy: msg => {
    sendToAllWindow("GuardBuy", msg.body);
  },
  onUserAction: msg => {
    sendToAllWindow("UserAction", msg.body);
  },
  onIncomeSuperChat: msg => {
    sendToAllWindow("SuperChat", msg.body);
  },
  onClose: () => {
    const wins = BrowserWindow.getAllWindows();
    wins.forEach(win => {
      win.webContents.send("blive:[Close]");
    });
  },
  onOpen: () => {
    const wins = BrowserWindow.getAllWindows();
    wins.forEach(win => {
      win.webContents.send("blive:[Open]");
    });
  },
  onError: () => {
    const wins = BrowserWindow.getAllWindows();
    wins.forEach(win => {
      win.webContents.send("blive:[Error]");
    });
  }
};
function sendToAllWindow(event, data) {
  const wins = BrowserWindow.getAllWindows();
  wins.forEach(win => {
    win.webContents.send(`blive:[${event}]`, data);
  });
}
let instance = null;
function startListenBlive(roomId) {
  if (!roomId) return Promise.reject("房间号必填");
  return new Promise((resolve, reject) => {
    instance?.close();
    instance = startListen(roomId, handler);
    resolve("ok");
  });
}
function stopListenBlive() {
  instance.close();
  return new Promise((resolve, reject) => {
    resolve("close");
  });
}

export { startListenBlive, stopListenBlive };
